# -* - coding: UTF-8 -* -
#import sys 
#reload(sys)
#sys.setdefaultencoding('utf8')

import threading,string,os
from time import sleep
from task import *
from sql.command import *
import logging

#从外部队列读取消息放入内部对列
class SqlCenter():  
	def __init__(self,file_name):
		self.cache_file=file_name
		self.commands = []
	
	#读取暂存的命令
	def load(self):
		if os.path.isfile(self.cache_file):
			f=open(self.cache_file,'r')
			for line in f:
				if line.strip():
					cmd=SQLCommand('')
					cmd.fromJson(line.strip())
					self.commands.append(cmd)
			f.close()
	
	#保存已有的命令
	def save(self):
		f=open(self.cache_file,'w')
		for c in self.commands:
			if not c.is_finish():
				line = c.toJson()
				f.write(line+"\n")
		# 获取队列 
		f.close()			
	
	#增加SQL命令
	def add(self,sql,data):
		logging.info(sql)
		cmd=SQLCommand(sql)
		#logging.info("SQLCommand")
		#logging.info(cmd)
		self.commands.append(cmd)
		
	
	#增加其它命令
	def add_other(self,data):
		pass
		
	#执行命令
	def execute(self,task):
		for c in self.commands:
			if not c.is_finish():
				ret=c.execute(task)
				if ret==0:
					return True
			else:
				self.commands.remove(c)
		return False